package com.pig.easy.bpm.mysql.aspet;

import com.pig.easy.bpm.mysql.annotation.DataSource;
import com.pig.easy.bpm.mysql.reister.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;

/**
 * todo:
 *
 * @author : pig
 * @date : 2020/5/9 10:23
 */

@Aspect
@Slf4j
@Order(-1)
public class DynamicDataSourceAspect {

    @Pointcut("@annotation(com.pig.easy.bpm.mysql.annotation.DataSource)")
    public void pointCut() {

    }

    @Before("pointCut() && @annotation(dataSource)")
    public void changeDataSource(DataSource dataSource) {
        if (!DynamicDataSourceContextHolder.containsDataSource(dataSource.name())) {
            if(log.isDebugEnabled()){
                log.debug("dataSource " + dataSource.name() + " not exits" );
            }
        } else {
            if(log.isDebugEnabled()) {
                log.debug("changeDataSource：" + dataSource.name());
            }
            DynamicDataSourceContextHolder.setDataSourceType(dataSource.name());
        }
    }

    @After("pointCut() &&  @annotation(dataSource)")
    public void clearDataSource(DataSource dataSource) {
        if(log.isDebugEnabled()) {
            log.debug("clearDataSource：" + dataSource.name());
        }
        DynamicDataSourceContextHolder.clearDataSourceType();
    }

}
